//************************************************************************
//Developed by Guo Ming Li 2009/2010
//Source code:
//  The source code may be freely modified or used but this credit section may not be removed 
//  The original author must be notified of any modifications plus a copy of 
//  the changed source code
//Contact info: mailto://gming.li@gmail.com
//************************************************************************
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.BizTalk.ExplorerOM;

namespace GML.BizTalk.OperationManager.DeploymentManager
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            GML.BizTalk.OperationManager.Library.Logger.Configure();
        }

        private GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations msbtsOps = new GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations();
        private List<GML.BizTalk.OperationManager.MSBTSOperations.Environment> envInfo = new List<GML.BizTalk.OperationManager.MSBTSOperations.Environment>();
        private List<string> sEnvInfo = new List<string>();
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                GML.BizTalk.OperationManager.MSBTSOperations.Environment env = new GML.BizTalk.OperationManager.MSBTSOperations.Environment();
                env.BtsDbServerName = this.tbDBSvrName.Text.Trim();
                env.BtsManagmentDbName = this.tbMgntDBName.Text.Trim();
                env.EnvID = this.tbEnvID.Text.Trim();
                List<MSBTSOperations.BtsServer> lBtsServers = new List<MSBTSOperations.BtsServer>();
                string [] sBtsServers = this.tb_btsServerNames.Text.Trim().Split(",".ToCharArray());
                foreach (string sBtsServer in sBtsServers)
                {
                    MSBTSOperations.BtsServer btsServer = new MSBTSOperations.BtsServer();
                    btsServer.ComputerName = sBtsServer;
                    lBtsServers.Add(btsServer);
                }
                env.BtsServers = lBtsServers.ToArray();
                envInfo.Add(env);

                sEnvInfo.Add(this.tbEnvID.Text.Trim());
                this.lbEnvInfo.DataSource = null;
                this.lbEnvInfo.DataSource = sEnvInfo;

                this.cmbBindingEnv.DataSource = null;
                this.cmbBindingEnv.DataSource = sEnvInfo;

                this.cmbEnvInfo4AddingFileSource.DataSource = null;
                this.cmbEnvInfo4AddingFileSource.DataSource = sEnvInfo;

                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string sEnvTobeDeleted = this.lbEnvInfo.SelectedItem.ToString();
                sEnvInfo.Remove(sEnvTobeDeleted);

                this.lbEnvInfo.DataSource = null;
                this.lbEnvInfo.DataSource = sEnvInfo;

                this.cmbBindingEnv.DataSource = null;
                this.cmbBindingEnv.DataSource = sEnvInfo;

                this.cmbEnvInfo4AddingFileSource.DataSource = null;
                this.cmbEnvInfo4AddingFileSource.DataSource = sEnvInfo;

                int idx = 0;
                bool isFound = false;
                foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in envInfo)
                {
                    if (env.EnvID.Equals(sEnvTobeDeleted))
                    {
                        isFound = true;
                        break;
                    }
                    else
                    {
                        idx++;
                    }
                }
                if (isFound)
                {
                    envInfo.RemoveAt(idx);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private List<GML.BizTalk.OperationManager.MSBTSOperations.Operation> listOfOp = null;
        //private GML.BizTalk.OperationManager.MSBTSOperations.Operation op = null;
        //private List<GML.BizTalk.OperationManager.MSBTSOperations.Orchestration> listOfStartedOrch = null;
        private List<GML.BizTalk.OperationManager.MSBTSOperations.Orchestration> listOfOrchs = null;
        private void btGenerateXml_Click(object sender, EventArgs e)
        {
            try
            {
                this.tbGeneratedXml.Text = GetGeneratedXml(null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void btGenAndSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.saveFileDialog1.Filter = "Xml files (*.xml)|*.xml|All files (*.*)|*.*";
                this.saveFileDialog1.FilterIndex = 0;
                this.saveFileDialog1.ShowDialog();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
        private void saveFileDialog1_FileOK(object sender, CancelEventArgs e)
        {
            try
            {
                string s = GetGeneratedXml(saveFileDialog1.FileName);
                this.tbGeneratedXml.Text = s;
                using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
                {
                    sw.WriteLine(s);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private string GetGeneratedXml(string filename)
        {
            this.listOfOp = new List<GML.BizTalk.OperationManager.MSBTSOperations.Operation>();
            GML.BizTalk.OperationManager.MSBTSOperations.Operation op = null;

            try
            {
                //--------------------------------------------------
                int iExecSequence = 0;
                if (this.cbGenerateEnvInfo.Checked && this.envInfo != null)
                {
                    this.msbtsOps.EnvironmentInfo = this.envInfo.ToArray();
                }
                //--------------------------------------------------
                if (this.cb_gacVerification.Checked && this.envInfo != null)
                {
                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = GenerateGacVerification(); 
                    this.listOfOp.Add(op);
                    iExecSequence++;
                }
                //--------------------------------------------------
                if (this.cbEnableAllRcvLocation.Checked && this.envInfo != null)
                {
                    List<GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocation> instances = new List<GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocation>();
                    GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocation instance = null;
                    foreach (MSBTSOperations.Environment env in envInfo)
                    {
                        instance = new GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocation();
                        instance.ApplicatonName = this.cmbApplicationNames.SelectedItem.ToString().Trim();
                        instance.EnvID = env.EnvID;
                        instance.Action = GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocationActionType.ENABLE_ALL;
                        instances.Add(instance);
                    }

                    GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocations instancesArray = new GML.BizTalk.OperationManager.MSBTSOperations.ReceiveLocations();

                    instancesArray.ReceiveLocation = instances.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = instancesArray;
                    this.listOfOp.Add(op);
                    iExecSequence++;
                }
                //--------------------------------------------------
                if (this.cbStartAllSendPort.Checked && this.envInfo != null)
                {
                    List<GML.BizTalk.OperationManager.MSBTSOperations.SendPort> instances = new List<GML.BizTalk.OperationManager.MSBTSOperations.SendPort>();
                    GML.BizTalk.OperationManager.MSBTSOperations.SendPort instance = null;
                    foreach (MSBTSOperations.Environment env in envInfo)
                    {
                        instance = new GML.BizTalk.OperationManager.MSBTSOperations.SendPort();
                        instance.ApplicatonName = this.cmbApplicationNames.SelectedItem.ToString().Trim();
                        instance.EnvID = env.EnvID;
                        instance.Action = GML.BizTalk.OperationManager.MSBTSOperations.SendPortActionType.START_ALL;
                        instances.Add(instance);
                    }

                    GML.BizTalk.OperationManager.MSBTSOperations.SendPorts instancesArray = new GML.BizTalk.OperationManager.MSBTSOperations.SendPorts();

                    instancesArray.SendPort = instances.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = instancesArray;
                    this.listOfOp.Add(op);
                    iExecSequence++;
                
                    //------ do the same for send port groups

                    List<GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroup> spgInstances = new List<GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroup>();
                    GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroup spgInstance = null;
                    foreach (MSBTSOperations.Environment env in envInfo)
                    {
                        spgInstance = new GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroup();
                        spgInstance.ApplicatonName = this.cmbApplicationNames.SelectedItem.ToString().Trim();
                        spgInstance.EnvID = env.EnvID;
                        spgInstance.Action = GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroupActionType.START_ALL;
                        spgInstances.Add(spgInstance);
                    }

                    GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroups instancesArray2 = new GML.BizTalk.OperationManager.MSBTSOperations.SendPortGroups();

                    instancesArray2.SendPortGroup = spgInstances.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = instancesArray2;
                    this.listOfOp.Add(op);
                    iExecSequence++;

                }
                //--------------------------------------------------
                if (this.cbXml4OrchStateMgnt.Checked)
                {
                    //GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement osm = new GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement();
                    //this.listOfStartedOrch = GML.BizTalk.OperationManager.Library.OrchestrationStateManagement.GetStartedOrchestrations(this.cmbApplicationNames.SelectedItem.ToString().Trim(), this.tbFromDbSvrName.Text.Trim(), this.tbFromMgntDbname.Text.Trim());
                    //if (this.cbOrchs2Start.Checked && this.listOfStartedOrch != null)
                    //{
                    //    osm.Orchestrations = this.listOfStartedOrch.ToArray();
                    //}
                    //if (this.cbOrch2Unenlist.Checked && this.listOfStartedOrch != null)
                    //{
                    //    osm.UnenlistExclusions = this.listOfStartedOrch.ToArray();
                    //}
                    //if (this.listOfStartedOrch != null && (this.cbOrchs2Start.Checked || this.cbOrch2Unenlist.Checked))
                    //{
                    //    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    //    op.ExecSequence = iExecSequence;
                    //    op.Item = osm;
                    //    this.listOfOp.Add(op);
                    //    iExecSequence++;
                    //}

                    GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement osm = new GML.BizTalk.OperationManager.MSBTSOperations.OrchestrationStateManagement();
                    this.listOfOrchs = GML.BizTalk.OperationManager.Library.OrchestrationStateManagement.GetOrchestrations(this.GetSelectedBtsOrchestrations(), this.cmbApplicationNames.SelectedItem.ToString().Trim());
                    if (cbXml4OrchStateMgnt.Checked && this.listOfOrchs != null)
                    {
                        osm.Orchestrations = this.listOfOrchs.ToArray();
                    }
                    if (this.listOfOrchs != null && this.cbXml4OrchStateMgnt.Checked)
                    {
                        op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                        op.ExecSequence = iExecSequence;
                        op.Item = osm;
                        this.listOfOp.Add(op);
                        iExecSequence++;
                    }
                }


                //--------------------------------------------------
                if (this.cbGenerateDeployPolicy.Checked)
                {
                    GML.BizTalk.OperationManager.MSBTSOperations.RuleSetDeployment rulesetDeployment = new GML.BizTalk.OperationManager.MSBTSOperations.RuleSetDeployment();
                    List<GML.BizTalk.OperationManager.MSBTSOperations.BtsRuleSet> btsRuleSets = new List<GML.BizTalk.OperationManager.MSBTSOperations.BtsRuleSet>();
                    GML.BizTalk.OperationManager.MSBTSOperations.BtsRuleSet btsRuleSet = null;

                    if (this.clbPolicy2Deploy != null)
                    {
                        int i = this.clbPolicy2Deploy.Items.Count;
                        for (int j = 0; j < i; j++)
                        {

                            //for (int i = 0; i <= this.clbExpAssemblies.Items.Count - 1; i++)
                            //{
                            //    if (this.clbExpAssemblies.GetItemChecked(i))
                            //    {
                            //        this.listOfSelectedAssemblies2beExported.Add(this.clbExpAssemblies.Items[i].ToString());
                            //    }
                            //}

                            if (clbPolicy2Deploy.GetItemChecked(j))
                            {
                                string sPolicy = clbPolicy2Deploy.Items[j].ToString();
                                string[] sPolicyArray = sPolicy.Split('/');
                                string version = sPolicyArray[1];
                                string majorV = version.Substring(0, version.IndexOf(".")).Trim();
                                string minorV = version.Substring(version.IndexOf(".") + 1).Trim();
                                btsRuleSet = new GML.BizTalk.OperationManager.MSBTSOperations.BtsRuleSet();
                                btsRuleSet.Action = "Deploy";
                                btsRuleSet.RuleName = sPolicyArray[0];
                                btsRuleSet.MajorVersion = Convert.ToInt32(majorV);
                                btsRuleSet.MinorVersion = Convert.ToInt32(minorV);

                                btsRuleSets.Add(btsRuleSet);
                            }

                        }
                    }

                    if (this.clbPolicy2Undeploy != null)
                    {
                        int i = this.clbPolicy2Undeploy.Items.Count;
                        for (int j = 0; j < i; j++)
                        {
                            //if (clbPolicy2Undeploy.SelectedIndices.Contains(j))
                            if (clbPolicy2Undeploy.GetItemChecked(j))
                            {
                                string sPolicy = clbPolicy2Undeploy.Items[j].ToString();
                                string[] sPolicyArray = sPolicy.Split('/');
                                string version = sPolicyArray[1];
                                string majorV = version.Substring(0, version.IndexOf(".")).Trim();
                                string minorV = version.Substring(version.IndexOf(".") + 1).Trim();
                                btsRuleSet = new GML.BizTalk.OperationManager.MSBTSOperations.BtsRuleSet();
                                btsRuleSet.Action = "Undeploy";
                                btsRuleSet.RuleName = sPolicyArray[0];
                                btsRuleSet.MajorVersion = Convert.ToInt32(majorV);
                                btsRuleSet.MinorVersion = Convert.ToInt32(minorV);

                                btsRuleSets.Add(btsRuleSet);
                            }
                        }

                    }

                    rulesetDeployment.BtsRuleSet = btsRuleSets.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = rulesetDeployment;
                    this.listOfOp.Add(op);


                    iExecSequence++;
                }

                //--------------------------------------------------
                if (this.cbGenerateXml4BindingInfo.Checked && !string.IsNullOrEmpty(filename))
                {
                    GML.BizTalk.OperationManager.MSBTSOperations.BindingInfoCollection bindingInfos = new GML.BizTalk.OperationManager.MSBTSOperations.BindingInfoCollection();
                    List<GML.BizTalk.OperationManager.MSBTSOperations.BindingInfo> bindings = new List<GML.BizTalk.OperationManager.MSBTSOperations.BindingInfo>();
                    GML.BizTalk.OperationManager.MSBTSOperations.BindingInfo binding = new GML.BizTalk.OperationManager.MSBTSOperations.BindingInfo();

                    System.IO.FileInfo fileInfo = new FileInfo(filename);
                    if (this.cmbBindingGenTab.SelectedItem.ToString().Equals("FROM_DATABASE"))
                    {
                        string bindingfilename = this.cmbApplicationNames.SelectedItem.ToString() + ".BindingInfo." +
                                            Guid.NewGuid().ToString() + "." +
                                            GML.BizTalk.OperationManager.Library.Helper.GetDateTimeString(DateTime.Now) +
                                            ".xml";
                        binding.ApplicationName = this.cmbApplicationNames.SelectedItem.ToString();
                        binding.BtsManagementDbName = this.tbFromMgntDbname.Text;
                        binding.BtsSqlServerName = this.tbFromDbSvrName.Text;
                        binding.EnvID = this.cmbBindingEnv.SelectedItem.ToString();
                        binding.FileSource = bindingfilename;
                        binding.GroupLevel = this.cbExpAllBindings4group.Checked;
                        binding.GroupLevelSpecified = true;

                        bindings.Add(binding);
                        string fullName = fileInfo.Directory.FullName + System.IO.Path.DirectorySeparatorChar + bindingfilename;
                        this.GenerateBindingInfo(fullName);
                    }
                    else //"FROM_FILE"
                    {
                        if (sBindingFileSource != null)
                        {
                            foreach (string sEnvIDAndfilename in sBindingFileSource)
                            {
                                string sEnvID = sEnvIDAndfilename.Substring(0, sEnvIDAndfilename.IndexOf("|"));
                                string sFilesource = sEnvIDAndfilename.Substring(sEnvIDAndfilename.IndexOf("|")+1);
                                sEnvID = sEnvID.Trim();
                                sFilesource = sFilesource.Trim();

                                string sBindingFilenameOnly = Path.GetFileName(sFilesource);
                                string sNewFilepath = fileInfo.Directory.FullName + System.IO.Path.DirectorySeparatorChar + sBindingFilenameOnly;
                                if (!sNewFilepath.ToUpper().Equals(sFilesource.ToUpper()))
                                {
                                    File.Copy(sFilesource, sNewFilepath);
                                }
                                foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in envInfo)
                                {
                                    if (env.EnvID.Equals(sEnvID))
                                    {
                                        binding = new GML.BizTalk.OperationManager.MSBTSOperations.BindingInfo();
                                        binding.ApplicationName = this.cmbApplicationNames.SelectedItem.ToString().Trim();
                                        binding.BtsManagementDbName = env.BtsManagmentDbName;
                                        binding.BtsSqlServerName = env.BtsDbServerName;
                                        binding.EnvID = env.EnvID;
                                        binding.FileSource = Path.GetFileName(sNewFilepath);
                                        bindings.Add(binding);
                                        break;
                                    }
                                }
                            }
                        }                    
                    }

                    bindingInfos.BindingInfo = bindings.ToArray();
                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = bindingInfos;
                    this.listOfOp.Add(op);


                    iExecSequence++;
                }
                //--------------------------------------------------
                if (this.cbStartAllHostInstances.Checked && this.envInfo != null)
                {
                    List<GML.BizTalk.OperationManager.MSBTSOperations.HostInstance> instances = new List<GML.BizTalk.OperationManager.MSBTSOperations.HostInstance>();
                    GML.BizTalk.OperationManager.MSBTSOperations.HostInstance instance = null;
                    foreach (MSBTSOperations.Environment env in envInfo)
                    {
                        instance = new GML.BizTalk.OperationManager.MSBTSOperations.HostInstance();
                        instance.EnvID = env.EnvID;
                        instance.Action = GML.BizTalk.OperationManager.MSBTSOperations.HostInstanceActionType.START_ALL;
                        instances.Add(instance);
                    }

                    GML.BizTalk.OperationManager.MSBTSOperations.HostInstances instancesArray = new GML.BizTalk.OperationManager.MSBTSOperations.HostInstances();

                    instancesArray.HostInstance = instances.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = instancesArray;
                    this.listOfOp.Add(op);
                    iExecSequence++;
                }
                //--------------------------------------------------
                if (this.cbResumeSuspendedByAdmin.Checked && this.envInfo != null)
                {
                    List<GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstance> instances = new List<GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstance>();
                    GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstance instance = null;
                    foreach (MSBTSOperations.Environment env in envInfo)
                    {
                        instance = new GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstance();
                        instance.EnvID = env.EnvID;
                        instance.Action = GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstanceActionType.RESUME_ALL_ADMIN_SUSPENDED;
                        instances.Add(instance);
                    }

                    GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances instancesArray = new GML.BizTalk.OperationManager.MSBTSOperations.ServiceInstances();

                    instancesArray.ServiceInstance = instances.ToArray();

                    op = new GML.BizTalk.OperationManager.MSBTSOperations.Operation();
                    op.ExecSequence = iExecSequence;
                    op.Item = instancesArray;
                    this.listOfOp.Add(op);
                    iExecSequence++;
                }
                //--------------------------------------------------


                this.msbtsOps.Operation = listOfOp.ToArray();

                string s = GML.Common.Utilities.Xml.SerializeObject(this.msbtsOps, this.msbtsOps.GetType());
                return s.Substring(s.IndexOf("<"));
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                throw ex;
            }
         }

        private void btBrowseExpBindingFile_Click(object sender, EventArgs e)
        {
            try
            {
                this.saveFileDialog2.Filter = "Xml files (*.xml)|*.xml|All files (*.*)|*.*";
                this.saveFileDialog2.FilterIndex = 0;
                this.saveFileDialog2.ShowDialog();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void saveFileDialog2_FileOK(object sender, CancelEventArgs e)
        {
            this.tbExpBindingFilename.Text = saveFileDialog2.FileName;
        }


        List<string> listExpAssemblies = null;
        List<string> listOfSelectedAssemblies2beExported = new List<string>();
        private void cbExpBindings4SelectedAssemblies_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.cbExpBindings4SelectedAssemblies.Checked)
                {
                    if (listExpAssemblies == null)
                    {
                        listExpAssemblies = GML.BizTalk.OperationManager.Library.Applications.GetAssemblies(this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text, this.cmbApplicationNames.SelectedItem.ToString());
                    }
                    //else
                    //{
                    //    this.clbExpAssemblies.Items.AddRange(listExpAssemblies.ToArray());
                    //}
                    this.clbExpAssemblies.Items.AddRange(listExpAssemblies.ToArray());
                    this.clbExpAssemblies.Enabled = true;
                }
                else
                {
                    this.clbExpAssemblies.Items.Clear();
                    this.clbExpAssemblies.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                //throw ex;
            }
        }

        private void btEnableBindingInfoGeneration_Click(object sender, EventArgs e)
        {
            try
            {
                this.tbExpBindingFilename.Enabled = true;
                this.btBrowseExpBindingFile.Enabled = true;
                this.btGenerateBindingInfo.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void btGenerateBindingInfo_Click(object sender, EventArgs e)
        {
            GenerateBindingInfo(this.tbExpBindingFilename.Text);
            MessageBox.Show("Binding info is successfully exported to file {" + this.tbExpBindingFilename.Text.Trim()+ "}");

        }

        private bool GenerateBindingInfo(string filename2beExported)
        {
            try
            {
                if (string.IsNullOrEmpty(filename2beExported))
                {
                    MessageBox.Show("Binding Filename needs to be specified.");
                    return false;
                }

                if (this.cbExpBindings4SelectedAssemblies.Checked)
                {
                    for (int i = 0; i <= this.clbExpAssemblies.Items.Count - 1; i++)
                    {
                        if (this.clbExpAssemblies.GetItemChecked(i))
                        {
                            this.listOfSelectedAssemblies2beExported.Add(this.clbExpAssemblies.Items[i].ToString());
                        }
                    }
                }

                GML.BizTalk.OperationManager.Library.BtsBindingInfo.Export
                (this.cbExpAllBindings4group.Checked,
                    this.cbExpGlobalPartyInfo4Binding.Checked,
                    this.cbExportAllBindings4App.Checked,
                    this.tbFromDbSvrName.Text,
                    this.tbFromMgntDbname.Text,
                    this.cmbApplicationNames.SelectedItem.ToString(),
                    this.cbExpAllBindings4sendport.Checked,
                    this.cbExpAllBindings4receiveport.Checked,
                    (this.cbExpBindings4SelectedAssemblies.Checked ? (this.listOfSelectedAssemblies2beExported.ToArray()) : null),
                    filename2beExported
                );

                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                return false;
            }
        }

        private void cmbBindingEnv_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbExpGlobalPartyInfo4Binding_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void cmbBindingGenTab_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.cmbBindingGenTab.SelectedItem.ToString().Equals("FROM_DATABASE"))
                {
                    this.tabPage7.BringToFront();
                }
                else if (this.cmbBindingGenTab.SelectedItem.ToString().Equals("FROM_FILE"))
                {
                    this.tabPage8.BringToFront();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        List<string> sBindingFileSource = new List<string>();
        private void btnAddBindingFileSource_Click(object sender, EventArgs e)
        {
            try
            {
                string sEnvID = this.cmbEnvInfo4AddingFileSource.SelectedItem.ToString();
                string sFileSource = this.tbFileSource4GenFromFile.Text.Trim();
                if (!string.IsNullOrEmpty(sEnvID) && !string.IsNullOrEmpty(sFileSource))
                {
                    sBindingFileSource.Add(sEnvID + " | " + sFileSource);
                    this.lbFileSource4bindingFile.DataSource = null;
                    this.lbFileSource4bindingFile.DataSource = sBindingFileSource;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }

        }

        private void btRemoveBindingFileSource_Click(object sender, EventArgs e)
        {
            try
            {
                string sEnvTobeDeleted = this.lbFileSource4bindingFile.SelectedItem.ToString();
                sBindingFileSource.Remove(sEnvTobeDeleted);

                this.lbFileSource4bindingFile.DataSource = null;
                this.lbFileSource4bindingFile.DataSource = sBindingFileSource;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void btnBrowseBindingFileSource_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Multiselect = false;
            this.openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            this.tbFileSource4GenFromFile.Text = this.openFileDialog1.FileName;
        }

        Microsoft.BizTalk.ExplorerOM.PolicyCollection Policies = null;
        List<string> listOfPolicies = null;
        private void cbGenerateDeployPolicy_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbGenerateDeployPolicy.Checked)
                {
                    Policies = GML.BizTalk.OperationManager.Library.Applications.GetPolicyCollection(this.cmbApplicationNames.SelectedItem.ToString().Trim(), this.tbFromDbSvrName.Text.Trim(), this.tbFromMgntDbname.Text.Trim());
                    listOfPolicies = new List<string>();
                    string policy2beDisplayed = null;
                    foreach (Microsoft.BizTalk.ExplorerOM.Policy policy in Policies)
                    {
                        policy2beDisplayed = policy.Name + "/" + policy.MajorRevision + "." + policy.MinorRevision + "/" + (policy.Deployed ? "Deployed" : "Published");
                        listOfPolicies.Add(policy2beDisplayed);

                        clbPolicy2Deploy.Items.Add(policy2beDisplayed, !policy.Deployed);
                        clbPolicy2Undeploy.Items.Add(policy2beDisplayed);
                    }


                }
                else
                {
                    clbPolicy2Deploy.Items.Clear();
                    clbPolicy2Undeploy.Items.Clear();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }


        private void btGetAppNames_Click(object sender, EventArgs e)
        {
            RetrieveApplicationNames();
        }

        private void RetrieveApplicationNames()
        {
            try
            {
                this.cmbApplicationNames.DataSource = GML.BizTalk.OperationManager.Library.Applications.GetListOfApplicationNames(this.tbFromDbSvrName.Text.Trim(), this.tbFromMgntDbname.Text.Trim(), false);
                this.cmbApplicationNames.SelectedIndex = 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void tbFromDbSvrName_Leave(object sender, EventArgs e)
        {
            RetrieveApplicationNames();

        }

        private void tbFromMgntDbname_Leave(object sender, EventArgs e)
        {
            RetrieveApplicationNames();

        }

        private void btRemoveAllBindings_Click(object sender, EventArgs e)
        {
            try
            {
                GML.BizTalk.OperationManager.Library.BtsBindingInfo.RemoveAll(this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text, this.cmbApplicationNames.SelectedItem.ToString());
                MessageBox.Show("Successfully removed all bindings for application {" + this.cmbApplicationNames.SelectedItem.ToString() + "}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void btImportEnvInfoFromXml_Click(object sender, EventArgs e)
        {
            this.DeploymentXmlImportFileDialog.Multiselect = false;
            this.DeploymentXmlImportFileDialog.ShowDialog();

        }

        private void DeploymentXmlImportFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations oOps = null;
            GML.BizTalk.OperationManager.MSBTSOperations.Environment[] envInfos = null;
            XmlDocument oDoc = new XmlDocument();

            string sXmlFileName = this.DeploymentXmlImportFileDialog.FileName.Trim();

            try
            {
                oDoc.Load(sXmlFileName);

                oOps = (GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations)
                        GML.Common.Utilities.Xml.Deserialize2Object(oDoc.InnerXml.Trim(), typeof(GML.BizTalk.OperationManager.MSBTSOperations.MSBTSOperations));

                envInfos = oOps.EnvironmentInfo;
                foreach (GML.BizTalk.OperationManager.MSBTSOperations.Environment env in envInfos)
                {
                    envInfo.Add(env);
                    sEnvInfo.Add(env.EnvID);

                }
                this.lbEnvInfo.DataSource = null;
                this.lbEnvInfo.DataSource = sEnvInfo;

                this.cmbBindingEnv.DataSource = null;
                this.cmbBindingEnv.DataSource = sEnvInfo;

                this.cmbEnvInfo4AddingFileSource.DataSource = null;
                this.cmbEnvInfo4AddingFileSource.DataSource = sEnvInfo;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void cb_gacVerification_CheckedChanged(object sender, EventArgs e)
        {
        }

        private MSBTSOperations.GACVerificationFilter GetGACVerificationFilter()
        {
            MSBTSOperations.GACVerificationFilter verificationFilter = new MSBTSOperations.GACVerificationFilter();
            verificationFilter.CheckAssemblyName = cb_includeAssemblyName.Checked ? true : false;
            verificationFilter.CheckAssemblyVersion = cb_includeAssemblyVersion.Checked ? true : false;
            verificationFilter.CheckAssemblyCulture = cb_includeAssemblyCulture.Checked ? true : false;
            verificationFilter.CheckAssemblyPublicKeyToken = cb_includeAssemblyKey.Checked ? true : false;
            verificationFilter.CheckAssemblyFileSize = cb_includeAssemblyFileSize.Checked ? true : false;
            verificationFilter.CheckAssemblyFileVersion = cb_includeAssemblyFileVersion.Checked ? true : false;
            verificationFilter.CheckAssemblyProductVersion = cb_includeAssemblyProductVersion.Checked ? true : false;
            verificationFilter.CheckAssemblyPath = cb_includeAssemblyPaths.Checked ? true : false;
            verificationFilter.CheckCreateDate = cb_includeAssemblyCreateDate.Checked ? true : false;
            verificationFilter.CheckMachineName = cb_inlcudeMachineName.Checked ? true : false;
            return verificationFilter;

        }

        private MSBTSOperations.GACVerification GenerateGacVerification()
        {
            MSBTSOperations.GACVerification gacVerfication = new MSBTSOperations.GACVerification();
            MSBTSOperations.GACVerificationFilter verificationFilter = null;
            List<MSBTSOperations.GACEntry> gacEntries = new List<MSBTSOperations.GACEntry>();
            try
            {
                if (this.cb_gacVerification.Checked)
                {
                    verificationFilter = GetGACVerificationFilter();

                    for (int i = 0; i <= this.clb4GacVerification.Items.Count - 1; i++)
                    {
                        if (this.clb4GacVerification.GetItemChecked(i))
                        {
                            //this.listOfSelectedAssemblies2BeVerified.Add(this.clb4GacVerification.Items[i].ToString());
                            MSBTSOperations.GACEntry gacEntry = new MSBTSOperations.GACEntry(this.clb4GacVerification.Items[i].ToString());
                            foreach (MSBTSOperations.GACEntry xGacEntry in gacList.Assemblies)
                            {
                                if (xGacEntry.ToLongString(verificationFilter).Equals(this.clb4GacVerification.Items[i].ToString()))
                                {
                                    gacEntries.Add(xGacEntry);
                                    break;
                                }
                            }
                        }
                    }

                    gacVerfication.VerificationFilter = verificationFilter;
                    gacVerfication.Assemblies = gacEntries.ToArray();
                    gacVerfication.GACListFilter = this.tb_gacAssemblyFilter.Text.Trim();
                    return gacVerfication;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            return null;
        }

        List<string> listOfSelectedAssemblies2BeVerified = new List<string>();
        List<string> listOfAssembliesFromGac = new List<string>();
        Library.GACList gacList =null;
        private void bt_retrieveGacAssemblies_Click(object sender, EventArgs e)
        {
            
            string machineName = string.Empty;
            string filter = string.Empty;
            this.clb4GacVerification.Items.Clear();
            try
            {
                machineName = this.tb_gacBaseMachineName.Text.Trim().ToUpper();
                filter = this.tb_gacAssemblyFilter.Text.Trim()+"*";

                if (Library.NetTools.IsValidMachineName(this.tb_gacBaseMachineName.Text.Trim()))
                {
                    gacList = new Library.GACList(GetGACVerificationFilter());
                    gacList.LoadList(machineName, filter);
                    //listExpAssemblies = GML.BizTalk.OperationManager.Library.Applications.GetAssemblies(this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text, this.cmbApplicationNames.SelectedItem.ToString());
                    listOfAssembliesFromGac = gacList.AssembliesToString;
                }
                this.clb4GacVerification.Items.AddRange(listOfAssembliesFromGac.ToArray());
                this.clb4GacVerification.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                //throw ex;
            }

        }

        private void btnSelectAllAsmForVerification_Click(object sender, EventArgs e)
        {
            int icount = clb4GacVerification.Items.Count;
            for (int i = 0; i < icount; i++)
            {
                clb4GacVerification.SetItemChecked(i, true);
            }
        }

        private void btnUnSelectAllAsmForVerification_Click(object sender, EventArgs e)
        {
            int icount = clb4GacVerification.Items.Count;
            for (int i = 0; i < icount; i++)
            {
                clb4GacVerification.SetItemChecked(i, false);
            }
        }

        BtsOrchestrationCollection listOfBtsOrchs = null;
        List<string> listOfSelectedOrchs = null;
        List<string> listOfAvailableOrchs = null;
        private void cbXml4OrchStateMgnt_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.cbXml4OrchStateMgnt.Checked)
                {
                    listOfSelectedOrchs = new List<string>();
                    listOfAvailableOrchs = new List<string>();
                    listOfBtsOrchs = GML.BizTalk.OperationManager.Library.OrchestrationStateManagement.ListOrchestrations(this.cmbApplicationNames.SelectedItem.ToString(), this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text);
                    //if (listOfOrchs == null)
                    //{
                    //    //listOfOrchs = GML.BizTalk.OperationManager.Library.Applications.GetAssemblies(this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text, this.cmbApplicationNames.SelectedItem.ToString());
                    //}
                    //this.clbExpAssemblies.Items.AddRange(listExpAssemblies.ToArray());
                    //this.clbExpAssemblies.Enabled = true;
                    foreach (BtsOrchestration orch in listOfBtsOrchs)
                    {
                        listOfAvailableOrchs.Add(orch.AssemblyQualifiedName + " | " + orch.Status.ToString());
                    }
                    this.clb_Orchestrations.Items.AddRange(listOfAvailableOrchs.ToArray());
                    this.clb_Orchestrations.Enabled = true;

                }
                else
                {
                    //this.clbExpAssemblies.Items.Clear();
                    //this.clbExpAssemblies.Enabled = false;
                    this.clb_Orchestrations.Items.Clear();
                    this.clb_Orchestrations.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                //throw ex;
            }

            //string machineName = string.Empty;
            //string filter = string.Empty;
            //this.clb4GacVerification.Items.Clear();
            //try
            //{
            //    machineName = this.tb_gacBaseMachineName.Text.Trim().ToUpper();
            //    filter = this.tb_gacAssemblyFilter.Text.Trim() + "*";

            //    if (Library.NetTools.IsValidMachineName(this.tb_gacBaseMachineName.Text.Trim()))
            //    {
            //        gacList = new Library.GACList(GetGACVerificationFilter());
            //        gacList.LoadList(machineName, filter);
            //        //listExpAssemblies = GML.BizTalk.OperationManager.Library.Applications.GetAssemblies(this.tbFromDbSvrName.Text, this.tbFromMgntDbname.Text, this.cmbApplicationNames.SelectedItem.ToString());
            //        listOfAssembliesFromGac = gacList.AssembliesToString;
            //    }
            //    this.clb4GacVerification.Items.AddRange(listOfAssembliesFromGac.ToArray());
            //    this.clb4GacVerification.Enabled = true;

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            //    //throw ex;
            //}

        }

        private void btn_selectAllOrchs_Click(object sender, EventArgs e)
        {
            int icount = clb_Orchestrations.Items.Count;
            for (int i = 0; i < icount; i++)
            {
                clb_Orchestrations.SetItemChecked(i, true);
            }
        }

        private void btn_unselectAllOrchs_Click(object sender, EventArgs e)
        {
            int icount = clb_Orchestrations.Items.Count;
            for (int i = 0; i < icount; i++)
            {
                clb_Orchestrations.SetItemChecked(i, false);
            }
        }

        private List<BtsOrchestration> GetSelectedBtsOrchestrations()
        {
            List<BtsOrchestration> result = new List<BtsOrchestration>();
            try
            {
                if (this.cbXml4OrchStateMgnt.Checked)
                {
                    

                    for (int i = 0; i <= this.clb_Orchestrations.Items.Count - 1; i++)
                    {
                        if (this.clb_Orchestrations.GetItemChecked(i))
                        {
                            string asmQualifiedOrchName_andStatus = clb_Orchestrations.Items[i].ToString();
                            string asmQualifiedOrchName = clb_Orchestrations.Items[i].ToString().Substring(0, asmQualifiedOrchName_andStatus.IndexOf("|")).Trim();

                            foreach (BtsOrchestration orch in listOfBtsOrchs)
                            {
                                if (orch.AssemblyQualifiedName.Equals(asmQualifiedOrchName))
                                {
                                    result.Add(orch);
                                    break;
                                }
                            }
                        }
                    }

                }
                return result;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                return null;
            }
        }


    }
}